<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>聊天与纠纷处理</h2>
    </div>

    <!-- WebSocket连接按钮 -->
    <div class="ws-connection-button">
      <button @click="connectWebSocketHandler" :disabled="ws">连接 WebSocket</button>
    </div>

    <!-- 输入框区域 -->
    <div class="input-fields">
      <div>
        <label for="receiverId">Receiver ID:</label>
        <input v-model="receiverId" id="receiverId" type="text" placeholder="输入ReceiverId">
      </div>
      <div>
        <label for="orderId">Order ID:</label>
        <input v-model="orderId" id="orderId" type="text" placeholder="输入OrderId">
      </div>
      <div>
        <label for="taskId">Task ID:</label>
        <input v-model="taskId" id="taskId" type="text" placeholder="输入TaskId">
      </div>
      <div>
        <label for="disputeId">Dispute ID:</label>
        <input v-model="disputeId" id="disputeId" type="text" placeholder="输入DisputeId">
      </div>
      <div>
        <label for="userId">User ID:</label>
        <input v-model="userId" id="userId" type="text" placeholder="输入UserId">
      </div>
      <div>
        <label for="adminId">Admin ID:</label>
        <input v-model="adminId" id="adminId" type="text" placeholder="输入AdminId">
      </div>
      <div>
        <label for="imageUrl">Image URL:</label>
        <input v-model="imageUrl" id="imageUrl" type="text" placeholder="输入Image URL (可选)">
      </div>
    </div>

    <!-- 聊天消息显示区域 -->
    <div class="chat-messages" ref="messageList">
      <div v-for="(msg, index) in messages" :key="index" class="chat-message">
        <p><strong>{{ msg.senderName }}:</strong> {{ msg.content }}</p>
        <img v-if="msg.imageUrl" :src="msg.imageUrl" alt="图片" class="message-image">
      </div>
    </div>

    <!-- 发送消息区域 -->
    <div class="chat-input">
      <textarea v-model="message" placeholder="输入消息..." @keyup.enter="sendMessage"></textarea>
      <button @click="sendMessage" :disabled="!message.trim()">发送</button>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import { connectWebSocket, sendMessage} from '../api/chat';

export default {
  data() {
    return {
        message: '',        // 用户输入的消息
        messages: [],       // 存储聊天消息
        senderId: 1,        // 默认 senderId
        role: 'admin',      // 默认 role
        orderId: '',        // orderId 通过输入框绑定
        taskId: '',         // taskId 通过输入框绑定
        disputeId: '',      // disputeId 通过输入框绑定
        adminId: '',        // adminId 通过输入框绑定
        receiverId: '',     // receiverId 通过输入框绑定
        userId: '',         // userId 通过输入框绑定
        imageUrl: '',       // imageUrl 通过输入框绑定
        ws: null,           // WebSocket 对象
    };
  },
  methods: {
    // 处理 WebSocket 接收到的消息
    handleIncomingMessage(messageData) {
        const { receiverId, orderId, taskId, disputeId, userId, adminId, content, imageUrl } = messageData;

        if (receiverId === undefined) {
          console.log('忽略 receiverId 为 undefined 的消息');
          return;
        }
        // 打印消息内容，确保正确接收
        console.log(`收到用户消息: ${content}`);
        console.log(`消息字段: receiverId=${receiverId}, orderId=${orderId}, taskId=${taskId}, disputeId=${disputeId}, userId=${userId}, adminId=${adminId}`);

        // 处理展示逻辑
        ElMessage.info(`收到来自用户(${userId})的消息: ${content}, receiverId: ${receiverId}, orderId: ${orderId}, taskId: ${taskId}, disputeId: ${disputeId}, adminId: ${adminId}`);

        // 将收到的消息推送到 messages 数组中
        this.messages.push({
            senderName: `用户(${userId}),receiverId(${receiverId}), orderId(${orderId}), taskId(${taskId}), disputeId(${disputeId}), userId(${userId}), adminId(${adminId})`,  // 根据 userId 来显示消息的发送者
            content: content,
            imageUrl: imageUrl || null  // 如果有图片 URL，处理显示
        });

        // 如果有图片 URL，可能需要在 UI 上展示图片
        if (imageUrl) {
            console.log(`图片URL: ${imageUrl}`);
        }

        // 滚动到消息的最新位置
        this.scrollToBottom();
    },

    // 连接 WebSocket
    connectWebSocketHandler() {
        this.senderId = 1;
        this.role = 'admin';

        connectWebSocket(this.senderId, this.role)
            .then((ws) => {
                this.ws = ws;
                ElMessage.success('WebSocket 连接成功');

                // 订阅 WebSocket 消息（根据后端实现，调用相应的处理方法）
                this.ws.onmessage = (event) => {
                    const messageData = JSON.parse(event.data);
                    this.handleIncomingMessage(messageData);
                };
            })
            .catch((error) => {
                ElMessage.error(`WebSocket 连接失败: ${error}`);
            });
    },

    // 发送消息
    sendMessage() {
        if (this.ws && this.message.trim()) {
            const messageData = {
                type: 'CHAT',
                receiverId: this.receiverId,
                orderId: this.orderId,
                taskId: this.taskId,
                disputeId: this.disputeId,
                userId: this.userId,
                adminId: this.adminId,
                content: this.message,
                imageUrl: this.imageUrl || null,
            };

            sendMessage(this.ws, messageData);
            this.messages.push({ senderName: 'Me', content: this.message });
            this.message = '';  // 清空输入框

            // 滚动到消息的最新位置
            this.scrollToBottom();
        } else {
            ElMessage.warning('WebSocket 未连接或消息为空');
        }
    },

    // 滚动到消息的底部
    scrollToBottom() {
      this.$nextTick(() => {
        const messageList = this.$refs.messageList;
        messageList.scrollTop = messageList.scrollHeight;
      });
    }
  }
};
</script>

<style scoped>
/* 样式与原样保持一致，只是增加了输入框区域 */
.chat-container {
  padding: 20px;
  max-width: 600px;
  margin: auto;
  background-color: #f9f9f9;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.chat-header {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.ws-connection-button {
  margin-bottom: 20px;
  text-align: center;
}

.ws-connection-button button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.ws-connection-button button:disabled {
  background-color: #ddd;
  cursor: not-allowed;
}

.ws-connection-button button:hover:enabled {
  background-color: #45a049;
}

.input-fields {
  margin-bottom: 20px;
}

.input-fields div {
  margin-bottom: 10px;
}

.input-fields label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
}

.input-fields input {
  width: 100%;
  padding: 10px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.chat-messages {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 10px;
  border-radius: 10px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
}

.chat-message {
  margin-bottom: 15px;
  font-size: 14px;
  color: #555;
}

.chat-message strong {
  color: #1e88e5;
}

.chat-input {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chat-input textarea {
  flex: 1;
  padding: 12px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 8px;
  resize: none;
  transition: border-color 0.3s ease;
}

.chat-input textarea:focus {
  border-color: #4CAF50;
  outline: none;
}

.chat-input button {
  padding: 12px 20px;
  font-size: 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.chat-input button:disabled {
  background-color: #ddd;
  cursor: not-allowed;
}

.chat-input button:hover:enabled {
  background-color: #45a049;
}

@media (max-width: 768px) {
  .chat-container {
    padding: 15px;
  }

  .chat-input textarea {
    font-size: 14px;
  }

  .chat-input button {
    font-size: 14px;
  }
}
</style>
